package others;

public class TestOffer704 {

    //给定一个n个元素有序的（升序）整型数组nums 和一个目标值target ，写一个函数搜索nums中的 target，如果目标值存在返回下标，否则返回 -1。
    //输入: nums = [-1,0,3,5,9,12], target = 9
    //输出: 4
    //解释: 9 出现在 nums 中并且下标为 4


    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length ;

        while(right > left){
            int middle = left + ((right - left) / 2);
            if(nums[middle] > target){
                right = middle ;
            }
            else if(nums[middle] < target){
                left = middle + 1;
            }else {
                return middle;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int a[] = {-1,0,3,5,9,12};
        int target = 2;
        System.out.println(search(a, target));
    }
}
